// 1. React核心库
import React, { useState } from 'react';

// 2. UI组件库 - 按字母顺序排列
import {
  Card,
  Row,
  Col,
  Button,
  Form,
  Input,
  message,
  Typography,
  Steps,
} from 'antd';

// 3. 图标库
import {
  UserOutlined,
  LockOutlined,
  MailOutlined,
  UserAddOutlined,
  LoginOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';

// 5. 工具库
import { history } from '@umijs/max';

// 6. 项目内部模块
import { apiClients } from '@/services/apiClient';

// 解构常用子组件
const { Title, Text, Link } = Typography;

interface RegisterForm {
  username: string;
  email: string;
  first_name: string;
  last_name: string;
  password: string;
  password_confirm: string;
}

const Register: React.FC = () => {
  const [form] = Form.useForm();
  const [registerLoading, setRegisterLoading] = useState(false);

  // 注册请求
  const handleRegister = async (values: RegisterForm) => {
    try {
      setRegisterLoading(true);
      const response = await apiClients.auth.authRegisterCreate({
        userRegistrationRequest: values
      });

      console.log('🚀 注册API响应:', response);

      // 🔑 关键：手动提取data字段（不使用useRequest，无自动dataField处理）
      const userData = (response as any).data || response;

      if (userData) {
        message.success('注册成功！请登录您的账户');

        // 跳转到登录页面
        setTimeout(() => {
          history.push('/login');
        }, 1500);

        return userData;
      } else {
        throw new Error('注册失败：未获取到用户信息');
      }
    } catch (error: any) {
      const errorMessage = error?.response?.data?.message || error?.message || '注册失败';
      message.error(errorMessage);
      throw error;
    } finally {
      setRegisterLoading(false);
    }
  };

  const onFinish = (values: RegisterForm) => {
    handleRegister(values);
  };

  return (
    <div style={{
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '20px',
    }}>
      <Card
        style={{
          width: '100%',
          maxWidth: 500,
          boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)',
          borderRadius: '12px',
        }}
        bodyStyle={{ padding: '40px' }}
      >
        <div style={{ textAlign: 'center', marginBottom: '32px' }}>
          <div style={{
            width: '64px',
            height: '64px',
            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            borderRadius: '50%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            margin: '0 auto 16px',
          }}>
            <UserAddOutlined style={{ fontSize: '32px', color: 'white' }} />
          </div>
          <Title level={2} style={{ margin: 0, color: '#1f2937' }}>
            创建新账户
          </Title>
          <Text type="secondary">加入用户管理系统</Text>
        </div>

        <Steps
          current={0}
          size="small"
          style={{ marginBottom: '32px' }}
          items={[
            {
              title: '填写信息',
              icon: <UserOutlined />,
            },
            {
              title: '验证邮箱',
              icon: <MailOutlined />,
            },
            {
              title: '完成注册',
              icon: <CheckCircleOutlined />,
            },
          ]}
        />

        <Form
          form={form}
          name="register"
          onFinish={onFinish}
          autoComplete="off"
          layout="vertical"
          size="large"
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="first_name"
                label="名字"
                rules={[
                  { required: true, message: '请输入您的名字' },
                  { max: 30, message: '名字长度不能超过30位' },
                ]}
              >
                <Input placeholder="请输入名字" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="last_name"
                label="姓氏"
                rules={[
                  { required: true, message: '请输入您的姓氏' },
                  { max: 30, message: '姓氏长度不能超过30位' },
                ]}
              >
                <Input placeholder="请输入姓氏" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="username"
            label="用户名"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 3, message: '用户名长度至少3位' },
              { max: 150, message: '用户名长度不能超过150位' },
              { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' },
            ]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="请输入用户名"
              autoComplete="username"
            />
          </Form.Item>

          <Form.Item
            name="email"
            label="邮箱地址"
            rules={[
              { required: true, message: '请输入邮箱地址' },
              { type: 'email', message: '请输入有效的邮箱地址' },
            ]}
          >
            <Input
              prefix={<MailOutlined />}
              placeholder="请输入邮箱地址"
              autoComplete="email"
            />
          </Form.Item>

          <Form.Item
            name="password"
            label="密码"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 8, message: '密码长度至少8位' },
              { 
                pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{8,}$/,
                message: '密码必须包含大小写字母和数字，长度至少8位'
              },
            ]}
            hasFeedback
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请输入密码"
              autoComplete="new-password"
            />
          </Form.Item>

          <Form.Item
            name="password_confirm"
            label="确认密码"
            dependencies={['password']}
            rules={[
              { required: true, message: '请确认密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
            hasFeedback
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请再次输入密码"
              autoComplete="new-password"
            />
          </Form.Item>

          <Form.Item style={{ marginBottom: '16px' }}>
            <Button
              type="primary"
              htmlType="submit"
              loading={registerLoading}
              block
              size="large"
              icon={<UserAddOutlined />}
              style={{
                background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                border: 'none',
                height: '48px',
                borderRadius: '8px',
              }}
            >
              创建账户
            </Button>
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: 'center' }}>
            <Text type="secondary">
              已有账户？{' '}
              <Link 
                onClick={() => history.push('/login')}
                style={{ color: '#667eea' }}
              >
                立即登录
              </Link>
            </Text>
          </Form.Item>
        </Form>

        <div style={{ textAlign: 'center', marginTop: '24px' }}>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            注册即表示您同意我们的服务条款和隐私政策
          </Text>
        </div>
      </Card>
    </div>
  );
};

export default Register;
